package com.yanyeori.framework.log.common.interceptor;

import com.yanyeori.framework.log.common.constant.LogConst;
import com.yanyeori.framework.log.common.util.LogUtil;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LogInterceptor
 *
 * @author chenkuan 2022/11/23
 */
public class MdcInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        MDC.put(LogConst.SERVLET_PATH, request.getServletPath());
        MDC.put(LogConst.SERVICE_NAME, handlerMethod.getBeanType().getSimpleName());
        MDC.put(LogConst.METHOD, request.getMethod());
        if (!StringUtils.isEmpty(request.getHeader(LogConst.HEADER_PRE + LogConst.TRACE_ID))) {
            MDC.put(LogConst.TRACE_ID, request.getHeader(LogConst.HEADER_PRE + LogConst.TRACE_ID));
        } else if (!StringUtils.isEmpty(request.getAttribute(LogConst.TRACE_ID))) {
            MDC.put(LogConst.TRACE_ID, request.getAttribute(LogConst.TRACE_ID).toString());
        } else {
            MDC.put(LogConst.TRACE_ID, LogUtil.getTraceId());
        }
        return true;
    }
}
